import 'dart:io';

import 'package:FineArt/components/rounded_button.dart';
import 'package:FineArt/core/api/user_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/my/myclasslist.dart';
import 'package:FineArt/page/my/noticelist.dart';
import 'package:FineArt/page/splash/role_choose.dart';
import 'package:FineArt/page/tab/contactservice.dart';
import 'package:FineArt/page/tab/feedback.dart';
import 'package:FineArt/page/tab/mypageedit.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:package_info/package_info.dart';

class MyPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _MyPageState();
  }
}

class _MyPageState extends State<MyPage> {
  String versionName = "";
  String userName;
  Size _size;

  UserInfo userInfo;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        versionName = packageInfo.version + "." + packageInfo.buildNumber;
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getMyInfo();
  }

  @override
  Widget build(BuildContext context) {
    _size = MediaQuery.of(context).size;
    // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          toolbarHeight: 0,
          brightness: Brightness.dark,
          //   title: Text("MyPage"),
          //   automaticallyImplyLeading: false,
          //   centerTitle: true,
          elevation: 0,
          backgroundColor: Colors.red,
        ),
        body: Stack(

            // fit: StackFit.expand,
            children: [
              Positioned(
                child: buildHeader(),
                top: 0,
              ),
              Positioned(
                child: buildVip(),
                top: 160,
                width: _size.width,
              ),
              Positioned(child: _buildContainer(), top: 240),
            ]));
  }

  Widget _buildContainer() {
    return Container(
      color: Color(0xfff2f2f2),
      height: _size.height - 300,
      width: _size.width,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: _buildListChild(),
        ),
      ),
    );
  }

  List<Widget> _buildListChild() {
    return [
      //头像
      // buildHeader(),
      SizedBox(
        height: getPortraitSHeight(7),
      ),
      buildCommonItem("assets/images/icon_notice.png", "我的通知", () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return NoticeListPage();
        }));
      }, null),
      buildCommonItem(
          "assets/images/icon_admin_class.png", "我的班级", () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return ClassListPage();
        }));
      }, null),
      buildCommonItem("assets/images/icon_vip_label.png", "我的会员", () {

      }, null),

      SizedBox(
        height: getPortraitSHeight(7),
      ),
      buildCommonItem("assets/images/icon_service.png", "联系客服", () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return ContactServicePage();
        }));
      }, null),
      buildCommonItem("assets/images/icon_fankui.png", "反馈建议", () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return FeedBackPage();
        }));
      }, null),
      if (Platform.isAndroid)buildCommonItem(
          "assets/images/icon_check_update.png", "检测更新(" + versionName + ")",
          () {
        FlutterBugly.checkUpgrade();
      }, null),

      SizedBox(
        height: getPortraitSHeight(7),
      ),
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: RoundedButton(
          color: Colors.white,
          text: "退出",
          press: () {
            showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: Text('提示'),
                    content: Text('确认退出当前用户？'),
                    actions: <Widget>[
                      FlatButton(
                        child: Text('取消'),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      FlatButton(
                        child: Text('确认'),
                        onPressed: () {
                          //SystemNavigator.pop();
                          UserApi().logout();
                          SPUtils.clearSession();
                          Navigator.of(context).pop();
                          Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) {
                            return ChooseRole();
                          }));
                        },
                      ),
                    ],
                  );
                });
          },
          // decoration: BoxDecoration(
          //   color: Colors.white,
          // ),
          textColor: Colors.black,
        ),
      ),
    ];
  }

  ///构建头像
  Widget buildAvatar() {
    return Center(
      child: Container(
        margin: EdgeInsets.only(top: 10, bottom: 10),
        width: 100,
        height: 100,
      ),
    );
  }

  Widget buildHeader() {
    return Container(
      padding: EdgeInsets.only(top: 10),
      color: Colors.red,
      width: _size.width,
      height: 200,
      child: Column(
        children: [
          Text(
            "我的",
            style: TextStyle(fontSize: 18, color: Colors.white),
          ),
          Row(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                child: Image.asset("assets/images/bg_header.png", width: 80),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                      width: _size.width - 120,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            userInfo == null
                                ? ""
                                : userInfo.nickname ?? userInfo.nickname,
                            style: TextStyle(color: Colors.white, fontSize: 16),
                          ),
                          InkWell(
                            onTap: () {
                              // ToastUtils.toast(" edit");
                              Navigator.of(context).push(MaterialPageRoute(builder: (context){
                                      return EditMyPage();
                              }));
                            },
                            child: Text("编辑",
                                style: TextStyle(
                                    color: Colors.white, fontSize: 16)),
                          )
                        ],
                      )),
                  SizedBox(
                    height: 5,
                  ),
                  Row(
                    children: [
                      buildClasses(),
                      SizedBox(
                        width: 10,
                      ),
                      Container(
                        decoration: BoxDecoration(
                            color: Colors.green,
                            borderRadius: BorderRadius.all(Radius.circular(5))),
                        padding:
                            EdgeInsets.symmetric(vertical: 2, horizontal: 6),
                        child: Text(
                          "已激活",
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Row buildClasses() {
    if (userInfo == null) return Row();
    if(userInfo.classes == null) return Row();
    if (userInfo.classes.isEmpty) return Row();

    List<Container> classes = [];
    for (ClassInfo info in userInfo.classes) {
      Container c = Container(
        decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.all(Radius.circular(5))),
        padding: EdgeInsets.symmetric(vertical: 2, horizontal: 6),
        margin: EdgeInsets.only(right: 3),
        child: Text(
          info.classname,
          style: TextStyle(color: Colors.white),
        ),
      );

      classes.add(c);
    }

    if (classes.length > 2) classes = classes.sublist(0,2);

    return Row(children: classes);
  }

  Widget buildRoundText(
      String text, Function press, Color color, Color bgColor) {
    return InkWell(
      onTap: press,
      child: Container(
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.all(Radius.circular(25))),
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
        child: Text(
          text,
          style: TextStyle(color: color, fontSize: 15),
        ),
      ),
    );
  }

  Widget buildVip() {
    return Container(
      width: _size.width,
      margin: EdgeInsets.symmetric(vertical: 1, horizontal: getPortraitSWidth(12)),
      padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
      height: 80,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10), color: Colors.white),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "assets/images/icon_vip_my.png",
                width: 50,
                height: 40,
              ),
              Text(
                "VIP中心",
                style: TextStyle(fontSize: 14),
              )
            ],
          ),
          Text(
            "立即领取\n7天免费会员",
            style: TextStyle(fontSize: 14),
          ),
          buildRoundText("体验会员", () {
            ToastUtils.toast("体验会员");
          }, Colors.white, Colors.red),
        ],
      ),
    );
  }

  //构建通用item
  Widget buildCommonItem(
      String name, String itemContent, Function clickListener, noticeCount) {
    return InkWell(
      child: Container(
        color: Colors.white,
        margin: EdgeInsets.symmetric(horizontal: getPortraitSWidth(12)),
        padding:
            EdgeInsets.only(left: 15.0, right: 15.0, bottom: 12.0, top: 12.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Image.asset(
              name,
              width: 20,
              height: 20,
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 20.0),
                child: getBadgeText(itemContent, noticeCount),
              ),
            ),
            Icon(Icons.chevron_right),
          ],
        ),
      ),
      onTap: clickListener,
    );
  }

  Widget getBadgeText(String name, String count) {
    if (count == null) {
      return Text(
        name,
        style: TextStyle(color: Colors.black87),
      );
    }
    return Container(
        width: 20,
        child: Badge(
          badgeContent: Text(
            count,
            style: TextStyle(color: Colors.white),
          ),
          child: Text(
            name,
            style: TextStyle(color: Colors.black87),
          ),
        ));
  }

  void _getMyInfo() {
    UserApi().userInfo().then((res) {
      if (res.code == 200) {
        setState(() {
          this.userInfo = res.data;
        });
      }
    });
  }
}
